package com.igoal.admin.web;

import java.io.File;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;

import com.igoal.dto.NewsDTO;
import com.igoal.service.NewsManager;
import com.igoal.utils.ImageUtils;
import com.igoal.web.validator.AddNewsValidator;

@Deprecated
public class AdminAddNewsController extends AdminBaseFormController {
	@Autowired
	NewsManager newsManager;
	
	@Autowired
	AddNewsValidator addNewsValidator;

	public void setAddNewsValidator(AddNewsValidator addNewsValidator) {
		this.addNewsValidator = addNewsValidator;
		setValidator(this.addNewsValidator);
	}

	public AdminAddNewsController() {
		setCommandName("newsCommand");
		setCommandClass(NewsDTO.class);
		setFormView(getViewPrefix() + "addNews");
		setSuccessView("redirect:/admin/addNews.html");		
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		NewsDTO dto = new NewsDTO();
		dto.setCommentCount(0);
		dto.setIndex(1);
		return dto;
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		String username = getUserInSession();
		NewsDTO dto = (NewsDTO) command;
		
		BindingResult bindingResult = errors.getBindingResult();
		
		addNewsValidator.validate(command, bindingResult);
		
		if(errors.hasErrors()){
			return new ModelAndView(getFormView(), bindingResult.getModel());
		}
		
		MultipartFile avatarFile = dto.getAvatarFile();

		String avatar = writeAvatarFile(avatarFile);
		if (avatar != null) {
			dto.setAvatar(avatar);
		}

		newsManager.addNews(username, dto);
		return new ModelAndView(getSuccessView());
	}

	String writeAvatarFile(MultipartFile avatarFile) {
		if (avatarFile != null) {
			try {
				String serverPath = getServerPath();
				String repository = File.separator + "files" + File.separator + "_news_" + File.separator;
				String tmpDir = File.separator + "tmp";
				String name = Calendar.getInstance().getTime().getTime() + avatarFile.hashCode() + "";
				String tmpOutput = tmpDir + File.separator + name + getFileExtension(avatarFile.getOriginalFilename());
				String finalRepositoryPath = repository + name + getFileExtension(avatarFile.getOriginalFilename());
				String finalOutput = serverPath + finalRepositoryPath;
				File tmpOutputFile = new File(tmpOutput);
				File repositoryDir = new File(serverPath + repository);
				if(!repositoryDir.exists()){
					repositoryDir.mkdirs();
				}

				avatarFile.transferTo(tmpOutputFile);
				ImageUtils.scaleImageWidth(tmpOutput, finalOutput, 170);

				return finalRepositoryPath;
			} catch (Exception e) {
				logger.error(e);
			}
		}

		return null;
	}

	public String getServerPath() {
		String serverPath = getServletContext().getRealPath("");
		serverPath = serverPath.replace(File.separator + "ROOT", "");
		return serverPath;
	}

	public String getFileExtension(String filenameExtension) {
		int dotPos = filenameExtension.lastIndexOf(".");
		String extension = filenameExtension.substring(dotPos);
		return extension;
	}

	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException {
		// Convert multipart object to byte[]
		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
	}
}
